package com.pentalog.bo.impl;

import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.client.core.WebServiceMessageCallback;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.SoapBody;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.xml.transform.StringSource;

import com.pentalog.bo.ExSoapClient;
import com.pentalog.domain.BookRequest;
import com.pentalog.domain.BookResponse;

public class ExSoapClientImpl extends WebServiceGatewaySupport implements
		ExSoapClient {
	private static final Logger LOGGER = LoggerFactory.getLogger(ExSoapClientImpl.class);
	
	@Autowired
	protected RestTemplate restTemplate;
	
	public BookResponse getBook(String id) {
		String wsdlUri = "http://localhost:8080/SoapSpring/soap/bookservices/book.wsdl";
		final BookRequest bookRequest = new BookRequest();
		bookRequest.setItemCode(id);

		BookResponse bookResponse = (BookResponse) getWebServiceTemplate()
				.marshalSendAndReceive(wsdlUri, bookRequest, new WebServiceMessageCallback() {
					@Override
					public void doWithMessage(WebServiceMessage message) throws IOException,
							TransformerException {
						/*LOGGER.info("Callback start");
						LOGGER.info(bookRequest.toString());						
						// TODO Auto-generated method stub
						SoapMessage soapMessage = (SoapMessage)message;
		                SoapBody body = soapMessage.getSoapBody();
		                StringSource headerSource = new StringSource("<bookRequest xmlns=\"http://localhost:8080/SoapSpring/soap\"><itemCode>A2</itemCode></bookRequest>");
		                Transformer transformer = TransformerFactory.newInstance().newTransformer();
		                transformer.transform(headerSource, body.getPayloadResult());*/
					}
				});
		return bookResponse;
	}
	public BookResponse getBookRest(String code) {
		String wsdlUri = "http://localhost:8080/SoapSpring/rest/service";
		return restTemplate.getForObject( wsdlUri + "/{code}",
			       BookResponse.class, code );
	}
}

